/*
 *   此商城的的聊天系统采用uniapp官方websocket api： https://uniapp.dcloud.io/api/request/websocket
 *   uni.connectSocket  建立链接
 *   uni.onSocketOpen   监听WebSocket连接打开事件
 *   uni.onSocketMessage  监听WebSocket接受到服务器的消息事件
 *   uni.sendSocketMessage  通过 WebSocket 连接发送数据
 *  */
import {
    LIVESOCKET
} from "./../config/index";

let timer = null;

const im = (isReconent = false) => {
    uni.connectSocket({
        url: LIVESOCKET,
        header: {
            'content-type': 'application/json'
        },
        method: 'GET',
        success: res => {
            console.log(`Websocket尝试连接${LIVESOCKET}✅...`)
        },
        fail: res => {
            console.log(`${LIVESOCKET}连接尝试失败❌`, res)
            setTimeout(() => {
                im()
            }, 2000);
        }
    })

    uni.onSocketOpen(() => {
        console.info(`${LIVESOCKET} 连接打开onSocketOpen 开启心跳机制💚...`);
        timer = setInterval(() => {
            if (isReconent) {
                console.log('发送 心跳💚')
            }
            uni.sendSocketMessage({
                data: JSON.stringify({
                    type: "ping",
                    id: uni.getStorageSync("token"),
                }),
            });
        }, 9000);
    });


    uni.onSocketMessage((res) => {
        const data = JSON.parse(res.data);
        //console.log('心跳💚data', data);
        if (data.type === "init") {
            let client_id = data.data.client_id

            if (uni.getStorageSync("token") != '') {
                uni.sendSocketMessage({
                    data: JSON.stringify({
                        type: "bind_id",
                        id: uni.getStorageSync("token"),
                        client_id,
                    }),
                });
                uni.setStorageSync('client_id', client_id)
            }
        }

    });

    uni.onSocketClose(function (res) {
        console.log(res);
        console.log('WebSocket 已关闭！');
        // #ifdef MP-WEIXIN
        im();
        // #endif
    });
    uni.onSocketError(res => {
        clearInterval(timer);
        console.error(`📵${LIVESOCKET}WebSocket连接打开失败，请检查！`);
        im();
    });
}
export default im
